<template>
    <div class="comFlex">
        <div class="rightDiv comLeft25">
          <div style="padding-top: 30px;padding-left: 18px;">
             <el-row :gutter="24">
              <el-col :span="8">
                <div class="comFlex comFlexCenter">
                  <label class="wordNoBreak textRight comWidth78">角色名称:</label><el-input class="comWidth400" v-model="uName"></el-input>
                </div>
              </el-col>
              <el-col :span="8">
                <div class="comFlex comFlexCenter">
                  <label class="wordNoBreak textRight comWidth78">状态:</label>
                   <el-select
                    v-model="status"
                    placeholder="请选择"
                    size="large"
                  >
                    <el-option
                      v-for="item in statusOpt"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                </div>
              </el-col>
              <el-col :span="8">
                <el-button type="primary" :icon="Search" @click="getRoleData">查询</el-button>
                <el-button :icon="RefreshRight" @click="reset">重置</el-button>
              </el-col>
            </el-row>
            <div class="comTop20">
              <el-button round v-for="(item,i) in btnList" :key="i" :type="item.type" @click="item.func">
                {{ item.label }}
              </el-button>
            </div>
          </div>
            <Table @handleSizeChange="getRoleData" :columns="tableColumns" v-model:page="page" v-model:size="size" :total="totalData" :tableData="tableData" class="comTop10" style="padding-left: 20px;">
                 <template #opt="scope">
                    <el-button @click="item.func(scope)" :type="item.type" link v-for="(item,i) in btnArr" :key="i">
                        {{ item.label }}
                    </el-button>
                </template>
            </Table>
        </div>
        <comForm :rules="formRules" @save="saveForm" :popupWidth="650" @cancel="cancel" :value="formValue" v-model:dialogVisible="dialogVisible" :dialogTitle="dialogTitle" :formConfig="formConfig">

        </comForm>
         <el-dialog v-model="treeDialog" title="角色授权" width="800" style="height: 600px;">
            <el-checkbox v-model="expandAll" @change="expandFun($event, 'menu')">展开/折叠</el-checkbox>
            <el-checkbox v-model="selectAll" @change="selectFun($event, 'menu')">全选/全不选</el-checkbox>
            <el-tree
                  class="tree-border"
                  :data="treeData"
                  show-checkbox
                  ref="treeRef"
                  node-key="id"
                  :default-checked-keys="defaultExpandTree"
                  empty-text="加载中，请稍候"
                  :props="{ label: 'name', children: 'children' }"
               ></el-tree>
               <template #footer>
                <div class="dialog-footer">
                  <el-button @click="treeDialog = false">取消</el-button>
                  <el-button type="primary" @click="saveMenu">
                    提交
                  </el-button>
                </div>
              </template>
        </el-dialog>
    </div>
</template>
<script setup>
import comForm from '@/components/comForm.vue'
import Table from '@/components/Table.vue'
import { onMounted, reactive, ref,watch } from 'vue'
import {resetForm } from '@/tools/tools.js'
import { roleClass, UserService,menuClass } from '@/api/api'
import { RefreshRight, Search } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
onMounted(() => {
  getRoleData()
})
const defaultExpandTree = ref([])
const treeRef = ref(null)
const expandAll = ref(false)
const menuOptions = ref([])
const expandFun = (value) => {
   let treeList = menuOptions.value
    for (let i = 0; i < treeList.length; i++) {
      treeRef.value.store.nodesMap[treeList[i].id].expanded = value
    }
}
const selectFun = (value) => {
  treeRef.value.setCheckedNodes(value ? menuOptions.value : [])
}
/** 所有菜单节点数据 */
function getMenuAllCheckedKeys() {
  // 目前被选中的菜单节点
  let checkedKeys = treeRef.value.getCheckedKeys()
  // 半选中的菜单节点
  // let halfCheckedKeys = treeRef.value.getHalfCheckedKeys()
  // console.log('halfCheckedKeys', halfCheckedKeys);
  
  // checkedKeys.unshift.apply(checkedKeys)
  return checkedKeys
}
const saveMenu = () =>{
    let form = getMenuAllCheckedKeys().join(',')
    let params = {
        menuIds : form,
        roleId : roleId.value
    }
    roleClass.updateRoleMenu(params).then(res => {
      const { code} = res
      if(code == 0){
        ElMessage.success('授权成功!')
        expandAll.value = selectAll.value = treeDialog.value = false
        defaultExpandTree.value = []
      }else{
        ElMessage.error('授权失败!')
      }
    })
}
const getParentNode = (node, result, key) => {
  let isPass = node?.data?.label?.indexOf(key) !== -1
  isPass ? result.push(isPass) : ''
  if (!isPass && node.level !== 1 && node.parent) {
    return getParentNode(node.parent, result, key)
  }
}
const isExpand = ref(false)
const defaultProps = {
  children: 'children',
  label: 'name',
  value : 'id'
}
const checkList = ref([])
const keyword = ref('') // 搜索关键子
// 执行tree数据过滤
watch(keyword, (newVal) => {
  treeRef.value.filter(newVal)
})
const treeData = ref([])
const selectAll = ref(false)
const treeDialog = ref(false)
const reset = () => {
  uName.value = status.value = ''
  getRoleData()
}
const isAdd = ref(false)
const roleId = ref('')
const saveForm = () => { 
  if(isAdd.value == false){
    formValue.roleId = roleId.value
    roleClass.updateRole({...formValue}).then(res => {
      if(res.code == 0){
        ElMessage.success('更新成功!')
        resetForm(formValue)
        dialogVisible.value = false
        getRoleData()
      }
    })
  }else{
    roleClass.addRole({...formValue}).then(res => {
      if(res.code == 0){
        ElMessage.success('新增角色成功!')
        resetForm(formValue)
        dialogVisible.value = false
        getRoleData()
      }
    })
  }
}
const dialogVisible = ref(false)
const totalData = ref(0)
const statusOpt = ref([
  {
    label : '启用',
    value : '0'
  },
  {
    label : '禁用',
    value : '1'
  }
])
const uName = ref('')
const page = ref(1)
const size = ref(10)
const getRoleData = () => {
  let params = {
    current : page.value,
    size : size.value,
    username : uName.value,
  }
  roleClass.getRoleList(params).then(res => {
    if(res.code == 0){
      const {records,total} = res.data
      tableData.value = records
      totalData.value = total
    }
  })
}
const status = ref('')
const formRules = reactive(
  {
    
  }
)
const formConfig = reactive({
  labelWidth : 90,
  formItemList : [
    {
      label : '角色名称：',
      prop : 'roleName',
      type : 'input',
    },
    {
      label : '角色标识：',
      prop : 'roleCode',
      type : 'input',
    },
    {
      label : '描述：',
      prop : 'roleDesc',
      type : 'input',
    },
  ]
})
const cancel = () => {
  dialogVisible.value = false
  resetForm(formValue)
}
const formValue = reactive({
  roleName : '',
  roleCode : '',
  roleDesc : ''
})
const dialogTitle = ref('')
const btnList = ref([
  {
    label : '新增',
    func : () => {
      dialogTitle.value = '新增'
      dialogVisible.value = isAdd.value = true
    },
    type : 'warning',
  },
   {
    label : '删除',
    func : () =>{

    } ,
    type : 'success',
  },
])
const updateFun =(item) => {
  const { row} = item
  dialogTitle.value = '修改' 
  dialogVisible.value = true
  isAdd.value = false
  roleId.value = row.roleId
  formValue.roleCode = row.roleCode
  formValue.roleDesc = row.roleDesc
  formValue.roleName = row.roleName
}
const authFun = (item) => {
  treeDialog.value = true
  roleId.value = item.row.roleId
  // getMenuList
  // getUserMenu
  menuClass.getMenuList().then(res => {
    const { code, data} = res
    console.log('data', data);
    if(code == 0 && data){
      treeData.value = data
      menuOptions.value = data
      roleClass.getCurrentAuth(roleId.value).then(res => {
      if(res.code == 0){
        defaultExpandTree.value = []
        res.data.forEach(item => {
          defaultExpandTree.value.push(parseInt(item))
        })
      }
    })
    }
  })
}
const btnArr = ref([
    {
        label : '修改',
        func : updateFun,
        type : 'primary'
    },
    {
        label : '删除',
        func : (item) => {
          ElMessageBox.alert('确认删除么？', '删除', {
          confirmButtonText: '确认',
            callback: (action) => {
              roleClass.delRole([item.row.roleId]).then(res => {
                if(res.code == 0){
                  ElMessage.success('删除成功!')
                  getRoleData()
                }
              })
            },
          })
        },
        type : 'danger'
    },
    {
        label : '授权',
        func : authFun,
        type : 'primary'
    }
])
    const tableColumns = ref([
        {type : 'index'},
        {
            label : '角色名称',
            prop : 'roleName',
        },
        {
            label : '角色标识',
            prop : 'roleCode',
        },
        {
            label : '角色描述',
            prop : 'roleDesc',
        },
        // {
        //     label : '状态',
        //     prop : 'status',
        //     slot : 'status',
        //     width : 200
        // },
        {
            label : '创建时间',
            prop : 'createTime',
        },
        {
            label : '操作',
            width:200,
            slot : 'opt'
        },
    ])
    const tableData = ref([
    ])
</script>
<style scoped>
.rightDiv{
    width: 98%;
    height: 85vh;
    background-color: rgba(255,255,255,1);
    border: 0px solid rgba(187,187,187,1);
}
</style>